import { AppstoreOutlined, InfoCircleTwoTone, ManOutlined, PlusOutlined, UnorderedListOutlined, WomanOutlined } from '@ant-design/icons'
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components'
import { Button, Card, Col, Divider, Empty, Flex, Form, Input, Modal, Pagination, PaginationProps, Row, Select, Tag, Tooltip, message } from 'antd'
import React, { useState, useRef, useEffect } from 'react'
import AddSickbeds from './components/AddSickbeds';
import SickbedsInfo from './components/SickbedsInfo';
import EditSickbeds from './components/EditSickbeds';
import { delete_sickbed, get_sickbed_list, quash_sickbed } from '@/services/sickbeds';
import { get_platformuser_select } from '@/services/patient';

type GithubIssueItem = {
    code: string;
    id: number;
    patient_name: string;
    patient_sex: string;
    doctor_name: string;
    manage_name: string;
    create_time: string;
    bind_doctor: any;
};
const EstablishedSickbeds = () => {
    const actionRef = useRef<ActionType>();
    const [form] = Form.useForm();

    // 控制按钮的点击
    const [colorStatus, setColorStatus] = useState(true)
    // 存储分页
    const [current, setCurrent] = useState(1);
    // 存储责任医生下拉框数据
    const [doctors, setDoctors] = useState<any>([]);
    // 存储新建病床模态框的状态
    const [isAddModalOpen, setIsAddModalOpen] = useState(false)
    // 存储编辑病床模态框的状态
    const [isEditModalOpen, setIsEditModalOpen] = useState(false)
    // 存储详情模态框的状态
    const [isInfoModalOpen, setIsInfoModalOpen] = useState(false)
    // 存储当前项id
    const [id, setId] = useState<number>()
    // 存储撤床模态框的状态
    const [cancelVisible, setCancelVisible] = useState(false)
    // 存储删除床模态框的状态
    const [delVisible, setDelVisible] = useState(false)
    // 存储家庭病床视图列表
    const [viewList, setViewList] = useState([])
    // 存储视图列表总数
    const [totalCount, setTotalCount] = useState<number>()
    // 存储视图层医生下拉框
    const [viewDoctorList, setViewDoctorList] = useState([])

    // 控制新建病床模态框的显示与隐藏
    const isShowAddModal = (status: boolean) => {
        setIsAddModalOpen(status)
    }
    // 控制编辑病床模态框的显示与隐藏
    const isShowEditModal = (status: boolean) => {
        setIsEditModalOpen(status)
    }
    // 控制详情模态框的显示与隐藏
    const isShowInfoModal = (status: boolean) => {
        setIsInfoModalOpen(status)
    }
    // 控制撤床模态框的显示与隐藏
    const isShowCancelVisible = (status: boolean) => {
        setCancelVisible(status)
    }
    // 控制删除床模态框的显示与隐藏
    const isShowDelVisible = (status: boolean) => {
        setDelVisible(status)
    }

    const onChange: PaginationProps['onChange'] = (page) => {
        console.log(page);
        setCurrent(page);
        getSickBedsView(page)
    };

    const gridStyle: React.CSSProperties = {
        marginTop: '20px',
        borderRadius: '0',
        borderTop: "3px solid red",

    };

    // 获取责任医生下拉列表
    useEffect(() => {
        const getDoctorList = async () => {
            let res = await get_platformuser_select();
            let arr: any = [];
            res.data.map((item: { id: number; username: any }) => {
                arr[item.id] = { text: item.username };
            });
            setDoctors(arr);
            console.log('责任医生', res, arr);
        };
        getDoctorList();
        getViewDoctorList()
        getSickBedsView(1)
    }, []);

    // 获取视图页面责任医生列表
    const getViewDoctorList = async () => {
        let res = await get_platformuser_select();
        let arr: any = [];
        res.data.map((item: { id: number; username: any }) => {
            let temp: any = {}
            temp.value = item.id;
            temp.label = item.username;
            arr.push(temp)
        });
        setViewDoctorList(arr)

    }

    // 获取家庭病床列表
    const getSickBeds = async (params: {
        pageSize?: number | undefined;
        current?: number | undefined;
        keyword?: string | undefined;
    }) => {
        //默认分页参数和后端接口字段不匹配
        let request_body = {
            ...params,
            current: params.current,
            pageSize: params.pageSize,
        };
        let res = await get_sickbed_list(request_body)
        console.log('家庭病床列表', res);
        return {
            data: res.data.list,
            success: true,
            total: res.data.total_count,
        };
    }
    // 获取家庭病床视图列表
    const getSickBedsView = async (page = 1, params?: any) => {
        //默认分页参数和后端接口字段不匹配
        let request_body = {
            ...params,
            current: page,
            pageSize: 18,
        };
        let res: any = await get_sickbed_list(request_body)
        console.log('家庭病床视图列表', res);
        // return
        if (res.code == 200) {
            setViewList(res.data.list)
            setTotalCount(res.data.total_count)
            setCurrent(page)
        }
    }
    // 撤床确定回调
    const cancelOk = async () => {
        let request_body = {
            id,
        }
        const res: any = await quash_sickbed(request_body);
        if (res.msg == 'ok') {
            message.success('撤床成功');
            actionRef.current?.reload();
        } else {
            message.error(res.msg);
        }
        isShowCancelVisible(false);
    }
    // 删除床确定回调
    const delOk = async () => {
        let request_body = {
            id,
        };
        const res: any = await delete_sickbed(request_body);
        if (res.msg == 'ok') {
            message.success('删除成功');
            actionRef.current?.reload();
        } else {
            message.error(res.msg);
        }
        isShowDelVisible(false);
    }
    // 视图层列表筛选
    const searchViewList = async (values: any) => {
        getSickBedsView(1, values)
    }

    // 已建病床列表字段
    const columns: ProColumns<GithubIssueItem>[] = [
        {
            title: '序号',
            key: 'index',
            dataIndex: 'index',
            valueType: 'index',
            width: 48,
        },
        {
            title: '病床编号',
            dataIndex: 'code',
            key: 'code',
            align: 'center',
        },
        {
            title: '患者',
            dataIndex: 'patient_name',
            key: 'patient_name',
            align: 'center',
        },
        {
            title: '性别',
            dataIndex: 'patient_sex',
            key: 'patient_sex',
            align: 'center',
            hideInSearch: true,
            valueEnum: {
                0: {
                    text: '未知',
                },
                1: {
                    text: '男',
                },
                2: {
                    text: '女',
                },
            },
        },
        {
            title: '责任医生',
            dataIndex: 'bind_doctor',
            key: 'bind_doctor',
            align: 'center',
            hideInSearch: true,
            render: (_, record) => (
                <Tooltip title={record.bind_doctor.map((item: any) => item.username).join()}>
                    {record.bind_doctor.map((item: any) => item.username).join().length > 5
                        ? record.bind_doctor
                            .map((item: any) => item.username)
                            .join()
                            .substring(0, 5) + '...'
                        : record.bind_doctor.map((item: any) => item.username).join()}
                </Tooltip>
            ),
        },
        {
            title: '责任医生',
            dataIndex: 'doctor_id',
            key: 'doctor_id',
            align: 'center',
            hideInTable: true,
            valueType: 'select',
            valueEnum: doctors,
            fieldProps: {
                showSearch: true,
                filterOption: (input: any, option: any) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            },
        },
        {
            title: '创建人',
            key: 'manage_name',
            dataIndex: 'manage_name',
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '创建时间',
            key: 'create_time',
            dataIndex: 'create_time',
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            align: 'center',
            render: (text, record, _, action) => (
                <>
                    <Button
                        key="info"
                        type='link'
                        onClick={() => {
                            setId(record.id)
                            isShowInfoModal(true)
                        }}
                        disabled={record.patient_name ? false : true}
                    >
                        详情
                    </Button>
                    <Button
                        key="che"
                        type='link'
                        onClick={() => {
                            setId(record.id)
                            isShowCancelVisible(true)
                        }}
                        disabled={record.patient_name ? false : true}
                    >
                        撤床
                    </Button>
                    <Button
                        key="editable"
                        type='link'
                        onClick={() => {
                            setId(record.id)
                            isShowEditModal(true)
                        }}
                    >
                        编辑
                    </Button>
                    <Button
                        key="del"
                        type='link'
                        onClick={() => {
                            setId(record.id);
                            isShowDelVisible(true);
                        }}
                    >
                        删除
                    </Button></>

            ),
        },
    ]
    return (
        <PageContainer
            breadcrumb={false}
            header={{
                extra: [
                    <Button
                        key="check"
                        style={{ padding: '0 12px' }}
                        type="link"
                        icon={<UnorderedListOutlined style={{ color: colorStatus ? '#0062ff' : '#333', fontSize: '20px' }} />}
                        onClick={() => setColorStatus(true)}
                    >
                    </Button>,
                    <Button
                        key="submit"
                        style={{ padding: '0 12px' }}
                        type="link"
                        icon={<AppstoreOutlined style={{ color: !colorStatus ? '#0062ff' : '#333', fontSize: '20px' }} />}
                        onClick={() => { setColorStatus(false); getSickBedsView() }}
                    >
                    </Button>
                ],
            }}>
            {colorStatus ? <ProTable<GithubIssueItem>
                columns={columns}
                actionRef={actionRef}
                cardBordered
                request={async (params = {}) => getSickBeds(params)}
                editable={{
                    type: 'multiple',
                }}
                rowKey={(record) => record.id}
                search={{
                    labelWidth: 'auto',
                    collapseRender: false,
                    collapsed: false,
                    span: 6,
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                pagination={{
                    pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle="已建病床列表"
                toolBarRender={() => [
                    <Button
                        key="button"
                        icon={<PlusOutlined />}
                        onClick={() => {
                            isShowAddModal(true);
                        }}
                        type="primary"
                    >
                        新增
                    </Button>,
                ]}
            /> : <div style={{ minWidth: '1200px' }}>
                <div style={{ width: '100%', padding: '24px', minHeight: "80px", backgroundColor: "#ffffff", borderRadius: "10px" }}>
                    <Form
                        layout='inline'
                        form={form}
                        onFinish={(values) => searchViewList(values)}
                    >
                        <Form.Item label="病床编号" name='code'>
                            <Input placeholder="请输入病床编号" />
                        </Form.Item>
                        <Form.Item label="患者" name='patient_name'>
                            <Input placeholder="请输入患者姓名" />
                        </Form.Item>
                        <Form.Item label="责任医生" name='doctor_id'>
                            <Select style={{ width: '200px' }} placeholder="请选择责任医生" options={viewDoctorList}>
                            </Select>
                        </Form.Item>
                        <Form.Item>
                            <Flex wrap="wrap" gap="small">
                                <Button type="default" htmlType="reset" onClick={() => { getSickBedsView(1); setCurrent(1) }}>重置</Button>
                                <Button type="primary" htmlType="submit">搜索</Button>
                            </Flex>
                        </Form.Item>
                    </Form></div>
                {viewList.length > 0 ? <><Row gutter={16}>
                    {viewList.map((item: any) => <Col span={4} key={item.id}>
                        <Card title={item.code} bordered={false} extra={item.level ? <Tag style={{ width: '20px', height: '20px', marginTop: '5px' }} color={item.level == 1 ? '#0062ff' : item.level == 2 ? '#f5dd1e' : '#F70A0A'}></Tag> : <></>} style={{
                            marginTop: '20px', borderRadius: '0',
                            borderTop: item.patient_name && item.doctor_name ? '3px solid #0062FF' : '3px solid #DADDE5',
                            cursor: item.patient_name ? 'pointer' : '',
                        }}
                            onClick={() => {
                                if (item.patient_name) {
                                    setId(item.id)
                                    isShowInfoModal(true)
                                }
                            }}
                        >
                            <div style={{ display: 'flex', justifyContent: 'space-between', }}>
                                <div style={{ fontSize: '14px', color: '#999999' }}>患者</div>
                                <div>{item.patient_name ?
                                    <div style={{ display: 'flex', alignItems: "center", }}>
                                        <div style={{ marginRight: "5px" }}>{item.patient_name}</div>
                                        <img style={{ width: '14px', height: '14px' }} src={item.patient_sex == 1 ? '/man.png' : '/woman.png'} alt="" />
                                    </div> : <div style={{ fontSize: '14px', color: '#40444A' }}>--</div>}
                                </div>
                            </div>
                            <div>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: "20px" }}>
                                <div style={{ fontSize: '14px', color: '#999999' }}>医生</div>
                                {item.bind_doctor.length > 0 ? <div>
                                    <Tooltip title={item.bind_doctor.map((item: any) => item.username).join()}>
                                        {item.bind_doctor.map((item: any) => item.username).join().length > 5
                                            ? item.bind_doctor
                                                .map((item: any) => item.username)
                                                .join()
                                                .substring(0, 5) + '...'
                                            : item.bind_doctor.map((item: any) => item.username).join()}
                                    </Tooltip>
                                </div> : <div style={{ fontSize: '14px', color: '#40444A' }}>--</div>}
                            </div>
                        </Card>
                    </Col>)}
                </Row>
                    <Pagination showSizeChanger={false} showTotal={(total, range) => {
                        console.log(total, range);

                        return (`第${range[0]}-${range[1]}条/总共${total}条`);
                    }} current={current} onChange={onChange} total={totalCount} defaultPageSize={18} style={{ display: 'flex', justifyContent: "flex-end", marginTop: '20px' }} /></> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}

            </div>}
            {/* 新建病床模态框 */}
            {isAddModalOpen ? <AddSickbeds isAddModalOpen={isAddModalOpen} isShowAddModal={isShowAddModal} actionRef={actionRef}></AddSickbeds> : ""}
            {/* 病床详情模态框 */}
            {isInfoModalOpen ? <SickbedsInfo isInfoModalOpen={isInfoModalOpen} isShowInfoModal={isShowInfoModal} actionRef={actionRef} id={id}></SickbedsInfo> : ""}
            {/* 编辑病床模态框 */}
            {isEditModalOpen ? <EditSickbeds isEditModalOpen={isEditModalOpen} isShowEditModal={isShowEditModal} id={id} actionRef={actionRef}></EditSickbeds> : ""}
            {/* 撤床 */}
            <Modal
                title="撤床确认"
                open={cancelVisible}
                onOk={cancelOk}
                onCancel={() => isShowCancelVisible(false)}
            >
                <Divider />
                <p>
                    <InfoCircleTwoTone twoToneColor="#ffcc00" /> 确定要进行撤床操作吗？
                </p>
            </Modal>
            {/* 删除床 */}
            <Modal
                title="删除确认"
                open={delVisible}
                onOk={delOk}
                onCancel={() => isShowDelVisible(false)}
            >
                <Divider />
                <p>
                    <InfoCircleTwoTone twoToneColor="#ffcc00" /> 确定要进行删除操作吗？
                </p>
            </Modal>
        </PageContainer>
    )
}
export default EstablishedSickbeds